package org.dtp.endpoint;

import org.dtp.DynamicThreadPoolExecutor;
import org.dtp.DynamicThreadPoolManager;
import org.dtp.config.DynamicThreadPoolProperties;
import org.dtp.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @ClassName DynamicThreadPoolEndpoint
 * @Description 动态线程池信息端点
 * @Author wangyiqi
 * @Date 2021-08-11-20:43
 **/
@Endpoint(id = "dynamic-thread-pool")
public class DynamicThreadPoolEndpoint {

    @Autowired
    private DynamicThreadPoolManager dynamicThreadPoolManager;

    @Resource
    private DynamicThreadPoolProperties dynamicThreadPoolProperties;

    @ReadOperation
    public Map<String, Object> threadPools() {
        Map<String, Object> data = new HashMap<>(16);
        List<Map<String, Object>> threadPools = dynamicThreadPoolProperties.getExecutors().stream().map(p -> {
            DynamicThreadPoolExecutor executor = dynamicThreadPoolManager.getThreadPoolExecutor(p.getThreadPoolName());
            Map<String, Object> threadPoolInfoMap = JsonUtil.objectParseMap(p, HashMap.class);
            AtomicInteger rejectCount = dynamicThreadPoolManager.getRejectCount(p.getThreadPoolName());

            threadPoolInfoMap.put("activeCount", executor.getActiveCount());
            threadPoolInfoMap.put("completedTaskCount", executor.getCompletedTaskCount());
            threadPoolInfoMap.put("largestPoolSize", executor.getLargestPoolSize());
            threadPoolInfoMap.put("taskCount", executor.getTaskCount());
            threadPoolInfoMap.put("rejectCount", rejectCount == null ? 0 : rejectCount.get());
            threadPoolInfoMap.put("waitTaskCount", executor.getQueue().size());
            return threadPoolInfoMap;
        }).collect(Collectors.toList());
        data.put("threadPools", threadPools);
        return data;
    }
}
